package scau.zzf.base.shiro;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import scau.zzf.base.redis.RedisCacheUtil;
import scau.zzf.dictionary.LoginCode;

/**
 * Created by zzf on 2017/4/30.
 */
public class LoginHelper {
    @Autowired
    private static RedisCacheUtil<Session> sessionRedisCacheUtil;
    private static Logger logger = LogManager.getLogger(LoginHelper.class);
    public static LoginCode login(String username,String password) {
        logger.info("======进入登陆======");
        SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        token.setRememberMe(false);
        try {
            subject.login(token);
        } catch (UnknownAccountException ex) {
            logger.catching(ex);
            return LoginCode.USER_NO_EXIST;
        } catch (IncorrectCredentialsException ex) {
            logger.catching(ex);
            return LoginCode.INCORRECT;

        }
        return LoginCode.OPERATION_SUCCESS;
    }

    public static LoginCode logout() {
        Subject currentUser = SecurityUtils.getSubject();
        Long id = null;
        if (null != currentUser) {
            try {
                Session session = currentUser.getSession();
                if (null != session) {
                    id=(Long) session.getAttribute("CURRENT_USER");
                }
            } catch (InvalidSessionException e) {
                logger.error(e);
            }
        }
        if (id != null) {
            sessionRedisCacheUtil.delete(String.valueOf(id));
        }
        logger.info("用户{} 登出", currentUser.getPrincipal());
        currentUser.logout();
        return LoginCode.OPERATION_SUCCESS;
    }
}
